"""
待办事项API端点

功能说明：
1. 提供待办事项的CRUD操作
2. 支持多状态管理
3. 确保用户数据隔离
4. 提供统计信息查询
"""

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime

from app.database import get_db
from app.models.todo import Todo, TodoStatus
from app.schemas.todo import (
    TodoCreate, 
    TodoUpdate, 
    TodoResponse, 
    TodoListResponse,
    TodoStatsResponse,
    TodoBatchDeleteRequest,
    TodoQueryParams
)
from app.api.v1.endpoints.auth import get_current_user
from app.models.user import User

router = APIRouter()


@router.post("/", response_model=TodoResponse, summary="创建待办事项")
async def create_todo(
    todo_data: TodoCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    创建新的待办事项
    
    - **title**: 待办事项标题（必填，1-50字符）
    - **content**: 待办事项内容（可选，最多500字符）
    - **status**: 待办事项状态（默认：待完成）
    """
    try:
        def normalize_to_value(input_status) -> str:
            """Return lowercase enum value ('pending'/'in_progress'/'completed') from diverse inputs."""
            if hasattr(input_status, "value"):
                return input_status.value
            s = str(input_status)
            # Try NAME first (e.g., 'PENDING')
            try:
                return TodoStatus[s].value
            except Exception:
                # Then try VALUE directly (e.g., 'pending')
                return TodoStatus(s).value
        # 创建待办事项实例
        db_todo = Todo(
            user_id=current_user.id,
            title=todo_data.title,
            content=todo_data.content,
            # Store enum VALUE (lowercase) for DB alignment
            status=normalize_to_value(todo_data.status)
        )
        
        # 保存到数据库
        db.add(db_todo)
        db.commit()
        db.refresh(db_todo)
        
        return TodoResponse.from_orm(db_todo)
        
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"创建待办事项失败: {str(e)}")


@router.get("/", response_model=TodoListResponse, summary="获取待办事项列表")
async def get_todos(
    status: Optional[TodoStatus] = Query(None, description="状态筛选"),
    skip: int = Query(0, ge=0, description="跳过数量"),
    limit: int = Query(20, ge=1, le=100, description="限制数量"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取当前用户的待办事项列表
    
    - **status**: 按状态筛选（可选）
    - **skip**: 跳过数量（默认：0）
    - **limit**: 限制数量（默认：20，最大：100）
    """
    try:
        # 构建查询
        query = db.query(Todo).filter(Todo.user_id == current_user.id)
        
        # 状态筛选
        if status:
            query = query.filter(Todo.status == status)
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        todos = query.offset(skip).limit(limit).all()
        
        # 转换为响应格式
        todo_responses = [TodoResponse.from_orm(todo) for todo in todos]
        
        return TodoListResponse(
            items=todo_responses,
            total=total,
            skip=skip,
            limit=limit
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取待办事项列表失败: {str(e)}")


@router.get("/{todo_id}", response_model=TodoResponse, summary="获取待办事项详情")
async def get_todo(
    todo_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取指定待办事项的详情
    
    - **todo_id**: 待办事项ID
    """
    try:
        # 查询待办事项
        todo = db.query(Todo).filter(
            Todo.id == todo_id,
            Todo.user_id == current_user.id
        ).first()
        
        if not todo:
            raise HTTPException(status_code=404, detail="待办事项不存在或无权限访问")
        
        return TodoResponse.from_orm(todo)
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取待办事项详情失败: {str(e)}")


@router.put("/{todo_id}", response_model=TodoResponse, summary="更新待办事项")
async def update_todo(
    todo_id: int,
    todo_data: TodoUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    更新指定的待办事项
    
    - **todo_id**: 待办事项ID
    - **title**: 待办事项标题（可选）
    - **content**: 待办事项内容（可选）
    - **status**: 待办事项状态（可选）
    """
    try:
        # 查询待办事项
        todo = db.query(Todo).filter(
            Todo.id == todo_id,
            Todo.user_id == current_user.id
        ).first()
        
        if not todo:
            raise HTTPException(status_code=404, detail="待办事项不存在或无权限访问")
        
        # 更新字段
        update_data = todo_data.dict(exclude_unset=True)
        for field, value in update_data.items():
            if field == "status" and value is not None:
                # Store enum VALUE (lowercase)
                if hasattr(value, "value"):
                    setattr(todo, field, value.value)
                else:
                    try:
                        setattr(todo, field, TodoStatus[value].value)  # assume NAME
                    except Exception:
                        setattr(todo, field, TodoStatus(str(value)).value)  # assume VALUE
            else:
                setattr(todo, field, value)
        
        # 更新修改时间
        todo.update_time = datetime.utcnow()
        
        # 保存到数据库
        db.commit()
        db.refresh(todo)
        
        return TodoResponse.from_orm(todo)
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新待办事项失败: {str(e)}")


@router.delete("/{todo_id}", summary="删除待办事项")
async def delete_todo(
    todo_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    删除指定的待办事项
    
    - **todo_id**: 待办事项ID
    """
    try:
        # 查询待办事项
        todo = db.query(Todo).filter(
            Todo.id == todo_id,
            Todo.user_id == current_user.id
        ).first()
        
        if not todo:
            raise HTTPException(status_code=404, detail="待办事项不存在或无权限访问")
        
        # 删除待办事项
        db.delete(todo)
        db.commit()
        
        return {"message": "待办事项删除成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除待办事项失败: {str(e)}")


@router.delete("/batch", summary="批量删除待办事项")
async def batch_delete_todos(
    request: TodoBatchDeleteRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    批量删除待办事项
    
    - **todo_ids**: 待办事项ID列表
    """
    try:
        # 查询待办事项
        todos = db.query(Todo).filter(
            Todo.id.in_(request.todo_ids),
            Todo.user_id == current_user.id
        ).all()
        
        if not todos:
            raise HTTPException(status_code=404, detail="未找到可删除的待办事项")
        
        # 检查是否所有ID都存在
        found_ids = {todo.id for todo in todos}
        missing_ids = set(request.todo_ids) - found_ids
        
        if missing_ids:
            raise HTTPException(
                status_code=404, 
                detail=f"以下待办事项不存在或无权限访问: {list(missing_ids)}"
            )
        
        # 批量删除
        for todo in todos:
            db.delete(todo)
        
        db.commit()
        
        return {"message": f"成功删除 {len(todos)} 个待办事项"}
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"批量删除待办事项失败: {str(e)}")


@router.get("/stats/summary", response_model=TodoStatsResponse, summary="获取待办事项统计")
async def get_todo_stats(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取当前用户的待办事项统计信息
    
    返回各状态下的待办事项数量统计
    """
    try:
        # 查询各状态的数量
        total = db.query(Todo).filter(Todo.user_id == current_user.id).count()
        pending = db.query(Todo).filter(
            Todo.user_id == current_user.id,
            Todo.status == TodoStatus.PENDING
        ).count()
        in_progress = db.query(Todo).filter(
            Todo.user_id == current_user.id,
            Todo.status == TodoStatus.IN_PROGRESS
        ).count()
        completed = db.query(Todo).filter(
            Todo.user_id == current_user.id,
            Todo.status == TodoStatus.COMPLETED
        ).count()
        
        return TodoStatsResponse(
            total=total,
            pending=pending,
            in_progress=in_progress,
            completed=completed
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")
